<?php 

namespace Home\Controller;
use Think\Controller;
use Home\Controller\CommonController;
class IndexController extends CommonController
{
    public function index()
    {	

      $count = M('question')->count();

        $Page  = new \Think\Page($count,4);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show  = $Page->show();// 分页显示输出

        $sql = "select t1.*,t2.username from question t1 left join user t2 on t1.uid=t2.id order by t1.create_time desc limit $Page->firstRow,$Page->listRows";

        // $sql = "select * from question where id='3'";

        $list = M()->query($sql);

        // var_dump($list);

        foreach ($list as  &$row) {
            if($row['answer_num']>0){
                // var_dump($row);
                $row = array_merge($row,$this->newAnswer($row['id']));
                // var_dump($row);
            }
            $row['categorys'] = $this->getCategory($row['id']);
        }

        // var_dump($list);

        // exit;

        // var_dump($list);

        // exit;

        // $list = M('question')->order('create_time')->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign('list',$list);
        $this->assign('show',$show);
        $this->display();
    }


    public function newAnswer($qid)
    {
        $sql = "select t2.username,t2.id uid,t1.create_time from answer t1 left join  user t2 on t1.uid=t2.id  where t1.qid='{$qid}' order by t1.create_time  desc limit 1";

        return current(M()->query($sql));
    }

    public function getCategory($qid)
    {
        $sql = "select t2.id cid ,t2.cname from question_category t1 left join category t2 on t1.cid=t2.id where t1.qid='{$qid}'";
        return M()->query($sql);
    }
    
}
    




 ?>